home *** CD-ROM | disk | FTP | other *** search
/ Freelog 115 / FreelogNo115-MaiJuin2013.iso / Internet / Filezilla Server / FileZilla_Server-0_9_41.exe / source / AsyncSslSocketLayer.h < prev    next >
C/C++ Source or Header  |  2011-11-06  |  9KB  |  258 lines

  1. /*           CAsyncSslSocketLayer by Tim Kosse 
  2.           mailto: tim.kosse@filezilla-project.org)
  3.                  Version 2.0 (2005-02-27)
  4. -------------------------------------------------------------
  5.  
  6. Introduction
  7. ------------
  8.  
  9. CAsyncSslSocketLayer is a layer class for CAsyncSocketEx which allows you to establish SSL secured
  10. connections. Support for both client and server side is provided.
  11.  
  12. How to use
  13. ----------
  14.  
  15. Using this class is really simple. In the easiest case, just add an instance of
  16. CAsyncSslSocketLayer to your socket and call InitClientSsl after creation of the socket.
  17.  
  18. This class only has a couple of public functions:
  19. - int InitSSLConnection(bool clientMode);
  20.   This functions establishes an SSL connection. The clientMode parameter specifies wether the SSL connection 
  21.   is in server or in client mode.
  22.   Most likely you want to call this function right after calling Create for the socket.
  23.   But sometimes, you'll need to call this function later. One example is for an FTP connection
  24.   with explicit SSL: In this case you would have to call InitSSLConnection after receiving the reply
  25.   to an 'AUTH SSL' command.
  26.   InitSSLConnection returns 0 on success, else an error code as described below under SSL_FAILURE
  27. - Is UsingSSL();
  28.   Returns true if you've previously called InitClientSsl()
  29. - SetNotifyReply(SetNotifyReply(int nID, int nCode, int result);
  30.   You can call this function only after receiving a layerspecific callback with the SSL_VERIFY_CERT 
  31.   id. Set result to 1 if you trust the certificate and 0 if you don't trust it.
  32.   nID has to be the priv_data element of the t_SslCertData structure and nCode has to be SSL_VERIFY_CERT.
  33. - CreateSslCertificate(LPCTSTR filename, int bits, unsigned char* country, unsigned char* state,
  34.             unsigned char* locality, unsigned char* organization, unsigned char* unit, unsigned char* cname,
  35.             unsigned char *email, CString& err);
  36.   Creates a new self-signed SSL certificate and stores it in the given file
  37. - SendRaw(const void* lpBuf, int nBufLen, int nFlags = 0)
  38.   Sends a raw, unencrypted message. This may be useful after successful initialization to tell the other
  39.   side that can use SSL.
  40.  
  41. This layer sends some layerspecific notifications to your socket instance, you can handle them in
  42. OnLayerCallback of your socket class.
  43. Valid notification IDs are:
  44. - SSL_INFO 0
  45.   There are two possible values for param2:
  46.     SSL_INFO_ESTABLISHED 0 - You'll get this notification if the SSL negotiation was successful
  47.     SSL_INFO_SHUTDOWNCOMPLETE 1 - You'll get this notification if the SSL connection has been shut 
  48.                                   down successfully. See below for details.
  49. - SSL_FAILURE 1
  50.   This notification is sent if the SSL connection could not be established or if an existing 
  51.   connection failed. Valid values for param2 are:
  52.   - SSL_FAILURE_NONE 0 - Everything OK
  53.   - SSL_FAILURE_UNKNOWN 1 - Details may have been sent with a SSL_VERBOSE_* notification.
  54.   - SSL_FAILURE_ESTABLISH 2 - Problem during SSL negotiation
  55.   - SSL_FAILURE_LOADDLLS 4
  56.   - SSL_FAILURE_INITSSL 8
  57.   - SSL_FAILURE_VERIFYCERT 16 - The remote SSL certificate was invalid
  58.   - SSL_FAILURE_CERTREJECTED 32 - The remote SSL certificate was rejected by user
  59. - SSL_VERBOSE_WARNING 3
  60.   SSL_VERBOSE_INFO 4
  61.   This two notifications contain some additional information. The value given by param2 is a 
  62.   pointer to a null-terminated char string (char *) with some useful information.
  63. - SSL_VERIFY_CERT 2
  64.   This notification is sent each time a remote certificate has to be verified.
  65.   param2 is a pointer to a t_SslCertData structure which contains some information
  66.   about the remote certificate.
  67.   You have to set the reply to this message using the SetNotifyReply function.
  68.   
  69. Be careful with closing the connection after sending data, not all data may have been sent already.
  70. Before closing the connection, you should call Shutdown() and wait for the SSL_INFO_SHUTDOWNCOMPLETE
  71. notification. This assures that all encrypted data really has been sent.
  72.  
  73. License
  74. -------
  75.  
  76. Feel free to use this class, as long as you don't claim that you wrote it
  77. and this copyright notice stays intact in the source files.
  78. If you want to use this class in a commercial application, a short message
  79. to tim.kosse@filezilla-project.org would be appreciated but is not required.
  80.  
  81. This product includes software developed by the OpenSSL Project
  82. for use in the OpenSSL Toolkit. (http://www.openssl.org/)
  83.  
  84. Version history
  85. ---------------
  86.  
  87. Version 2.0:
  88. - Add server support
  89. - a lot of bug fixes
  90.  
  91. */
  92.  
  93. #ifndef ASYNCSSLSOCKETLEAYER_INCLUDED
  94. #define ASYNCSSLSOCKETLEAYER_INCLUDED
  95.  
  96. #ifndef _AFX
  97. #define CString CStdString
  98. #endif
  99.  
  100. #include "AsyncSocketExLayer.h"
  101. #include <openssl/ssl.h>
  102.  
  103. // Details of SSL certificate, can be used by app to verify if certificate is valid
  104. struct t_SslCertData
  105. {
  106.     struct t_Contact
  107.     {
  108.         TCHAR Organization[256];
  109.         TCHAR Unit[256];
  110.         TCHAR CommonName[256];
  111.         TCHAR Mail[256];
  112.         TCHAR Country[256];
  113.         TCHAR StateProvince[256];
  114.         TCHAR Town[256];
  115.         TCHAR Other[1024];
  116.     } subject, issuer;
  117.  
  118.     struct t_validTime
  119.     {
  120.         //Year, Month, day, hour, minute, second
  121.         int y,M,d,h,m,s;
  122.     } validFrom, validUntil;
  123.  
  124.     unsigned char hash[20];
  125.  
  126.     int verificationResult;
  127.     int verificationDepth;
  128.  
  129.     int priv_data; //Internal data, do not modify
  130. };
  131.  
  132. class CCriticalSectionWrapper;
  133. class CAsyncSslSocketLayer : public CAsyncSocketExLayer
  134. {
  135. public:
  136.     BOOL SetCertStorage(CString file);
  137.     CAsyncSslSocketLayer();
  138.     virtual ~CAsyncSslSocketLayer();
  139.  
  140.     void SetNotifyReply(int nID, int nCode, int result);
  141.     BOOL GetPeerCertificateData(t_SslCertData &SslCertData);
  142.  
  143.     bool IsUsingSSL();
  144.     int InitSSLConnection(bool clientMode, void* pContext = 0);
  145.  
  146.     static bool CreateSslCertificate(LPCTSTR filename, int bits, unsigned char* country, unsigned char* state,
  147.             unsigned char* locality, unsigned char* organization, unsigned char* unit, unsigned char* cname,
  148.             unsigned char *email, CString& err);
  149.  
  150.     int SetCertKeyFile(const char* cert, const char* key, const char* pass, CString* error = 0);
  151.  
  152.     // Send raw text, useful to send a confirmation after the ssl connection
  153.     // has been initialized
  154.     int SendRaw(const void* lpBuf, int nBufLen, int nFlags = 0);
  155.  
  156.     void* GetContext() { return m_ssl_ctx; }
  157.     
  158. private:
  159.     virtual void Close();
  160.     virtual BOOL Connect(LPCTSTR lpszHostAddress, UINT nHostPort );
  161.     virtual BOOL Connect(const SOCKADDR* lpSockAddr, int nSockAddrLen );
  162.     virtual void OnConnect(int nErrorCode);
  163.     virtual void OnReceive(int nErrorCode);
  164.     virtual void OnSend(int nErrorCode);
  165.     virtual void OnClose(int nErrorCode);
  166.     virtual int Receive(void* lpBuf, int nBufLen, int nFlags = 0);
  167.     virtual int Send(const void* lpBuf, int nBufLen, int nFlags = 0);
  168.     virtual BOOL ShutDown( int nHow = sends );
  169.     
  170.     void ResetSslSession();
  171.     void PrintSessionInfo();
  172.     BOOL ShutDownComplete();
  173.     int InitSSL();
  174.     void UnloadSSL();
  175.     bool PrintLastErrorMsg();
  176.     void ClearErrors();
  177.  
  178.     void TriggerEvents();
  179.  
  180.     //Will be called from the OpenSSL library
  181.     static void apps_ssl_info_callback(const SSL *s, int where, int ret);
  182.     static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx);
  183.     static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata);
  184.  
  185.     bool m_bUseSSL;
  186.     BOOL m_bFailureSent;
  187.  
  188.     //Critical section for thread synchronization
  189.     static CCriticalSectionWrapper m_sCriticalSection;
  190.  
  191.     // Status variables
  192.     static int m_nSslRefCount;
  193.     BOOL m_bSslInitialized;
  194.     int m_nShutDown;
  195.     BOOL m_nNetworkError;
  196.     int m_nSslAsyncNotifyId;
  197.     BOOL m_bBlocking;
  198.     BOOL m_bSslEstablished;
  199.     CString m_CertStorage;
  200.     int m_nVerificationResult;
  201.     int m_nVerificationDepth;
  202.     
  203.     static struct t_SslLayerList
  204.     {
  205.         CAsyncSslSocketLayer *pLayer;
  206.         t_SslLayerList *pNext;
  207.     } *m_pSslLayerList;
  208.  
  209.     // Handles to the SLL libraries
  210.     static HMODULE m_hSslDll1;
  211.     static HMODULE m_hSslDll2;
  212.  
  213.     // SSL data
  214.     SSL_CTX* m_ssl_ctx;    // SSL context
  215.     static std::map<SSL_CTX *, int> m_contextRefCount;
  216.     SSL* m_ssl;            // current session handle
  217.  
  218.     //Data channels for encrypted/unencrypted data
  219.     BIO* m_nbio;    //Network side, sends/received encrypted data
  220.     BIO* m_ibio;    //Internal side, won't be used directly
  221.     BIO* m_sslbio;    //The data to encrypt / the decrypted data has to go though this bio
  222.  
  223.     //Send buffer
  224.     char* m_pNetworkSendBuffer;
  225.     int m_nNetworkSendBufferLen;
  226.     int m_nNetworkSendBufferMaxLen;
  227.  
  228.     char* m_pRetrySendBuffer;
  229.     int m_nRetrySendBufferLen;
  230.  
  231.     bool m_mayTriggerRead;
  232.     bool m_mayTriggerWrite;
  233.     bool m_mayTriggerReadUp;
  234.     bool m_mayTriggerWriteUp;
  235.  
  236.     bool m_onCloseCalled;
  237.  
  238.     char* m_pKeyPassword;
  239. };
  240.  
  241. #define SSL_INFO 0
  242. #define SSL_FAILURE 1
  243. #define SSL_VERIFY_CERT 2
  244. #define SSL_VERBOSE_WARNING 3
  245. #define SSL_VERBOSE_INFO 4
  246.  
  247. #define SSL_INFO_ESTABLISHED 0
  248. #define SSL_INFO_SHUTDOWNCOMPLETE 1
  249.  
  250. #define SSL_FAILURE_UNKNOWN 0
  251. #define SSL_FAILURE_ESTABLISH 1
  252. #define SSL_FAILURE_LOADDLLS 2
  253. #define SSL_FAILURE_INITSSL 4
  254. #define SSL_FAILURE_VERIFYCERT 8
  255. #define SSL_FAILURE_CERTREJECTED 0x10
  256.  
  257. #endif // ASYNCSSLSOCKETLEAYER_INCLUDED
  258.